<template>
  <!-- 联想建议 -->
  <!-- 联想建议 -->
  <!-- 联想建议 -->
  <div class="search-suggestion">
    <van-cell
      v-for="(text, index) in suggestions"
      :key="index"
      icon="search"
      @click="$emit('search', text)"
    >
      <div v-html="highlight(text)" slot="title"></div
    ></van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
// lodash 支持按需加载，有利于打包结果优化
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},

  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    searchText: {
      // 监视的处理函数
      handler: debounce(function (val) {
        this.loadSearchSuggestion(val)
      }, 500),
      // 首次监视触发
      immediate: true
    }
  },

  data () {
    return {
      suggestions: [] // 搜索建议的数据
    }
  },

  computed: {},

  created () {},
  mounted () {},
  methods: {
    // 获取搜索建议的数据
    async loadSearchSuggestion (q) {
      try {
        const { data } = await getSearchSuggestion(q)
        this.suggestions = data.data.options
      } catch {
        this.$toast('获取失败')
      }
    },

    // 搜索关键字高亮
    highlight (text) {
      const newStr = this.searchText.replace(/([+?|])/g, '\\$1')
      const reg = new RegExp(newStr, 'gi')
      return text.replace(
        reg,
        `<span class="active">${this.searchText}</span>`
      )
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>
